from pathlib import Path
import json
import time
from .config import keywords_params
from .globals import g
from .log import logger

# path = Path('lib')
# if path.is_dir():
#     from .lib import *
# else:
#     from .lib import *


def log_default_warning(keyword, param, default_value):
    logger.info(f'关键字<{keyword}> 参数<{param}> 已使用默认值: "{default_value}"')


def get_keyword_param(data: dict, key, default=None, gvar=False):
    v = data.get(key, None)
    if gvar and v is None:
        v = g.var.get(key, None)
    if v is None and default is None:
        raise AssertionError(f'未获取到关键字参数:{key}')
    elif v is None:
        logger.info(f'关键字参数<{key}> 已使用默认值: "{default}"')
        return default
    else:
        return v


def replace_dict(data: dict):
    # 变量替换
    data_keys = data.keys()
    for key in data_keys:
        if key not in keywords_params:
            data[key] = replace(data[key])
    for k in keywords_params:
        if k in data_keys:
            data[k] = replace(data[k])
    # 键替换
    for k in data_keys:
        replaced = replace(k)
        if k != replaced:
            v = data.pop(k)
            data[replaced] = v


def replace_list(data):
    # 变量替换
    for i in range(len(data)):
        data[i] = replace(data[i])



def replace(data: str):
    """把测试步骤中参数值中的的变量替换成数据"""
    if data == '{}':
        return ''
    try:
        return data.format(**g.var)
    except KeyError as ecpt:
        logger.exception(f'变量{str(ecpt)}未被赋值，变量替换失败！')
        raise


def str2int(s):
    s = str(s).replace(',', '').split('.', 1)
    if len(s) == 2:
        dot = s[-1]
        assert int(dot) == 0
    return int(s[0])


def zero(s):
    if s and s[-1] == '0':
        s = s[:-1]
        s = zero(s)
    return s


def str2float(s, n=None):
    s = str(s).replace(',', '')
    number = s.split('.', 1)
    if n:
        f = float(s)
        return round(f, n), n

    dot = '0'
    if len(number) == 2:
        dot = number[-1]
        dot = zero(dot)
    f = float(number[0] + '.' + dot)

    return round(f, len(dot)), len(dot)


def f(v, e, n=2):
    '''
    判断2个 float 数值是否相同，类型可以是 str 或 float 
    v: 实际值，如：12.345, '1234.56', '1,234.5600' 
    e: 预期结果, 示例值同 v
    n: 小数点精确位数
    '''
    v = str(v).replace(',', '')
    e = str(e).replace(',', '') 
    _v = round(float(v), n)
    _e = round(float(e), n)
    assert round(_v, n) == round(_e, n)


def mkdir(p):
    path = Path(p)
    if not path.is_dir():
        path.mkdir(parents=True)


def json2dict(s):
    if isinstance(s, dict):
        return s
    s = str(s)
    d = {}
    try:
        d = json.loads(s)
    except:
        try:
            d = eval(s)
        except:
            s = s.replace('true', 'True').replace('false', 'False').replace(
                'null', 'None').replace('none', 'None')
            d = eval(s)
    return d


def compare(data, real):
    if isinstance(data, str):

        if data.startswith('#'):
            assert data[1:] != str(real)
            return
        elif data.startswith(':'):
            exec('v=real;'+data[1:])
            return
                    
        assert isinstance(real, str)

        if data.startswith('*'):
            assert data[1:] in real
            return
        elif data.startswith('^'):
            assert real.startswith(data[1:])
            return
        elif data.startswith('$'):
            assert real.endswith(data[1:])
            return

        elif data.startswith('\\'):
            data = data[1:]

        assert data == real

    elif isinstance(data, int):
        assert isinstance(real, int)
        assert data == real
    elif isinstance(data, float):
        assert isinstance(real, float)
        data, p1 = str2float(data)
        real, p2 = str2float(real)
        p = min(p1, p2)
        assert round(data, p) == round(real, p)
    else:
        assert data == real


def timestamp():
    # js 格式的时间戳
    return int(time.time() * 1000)
